package com.oracle.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.oracle.mapper.RecordMapper;
import com.oracle.pojo.Record;
import com.oracle.service.RecordService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class RecordServiceImpl implements RecordService {

    @Autowired
    private RecordMapper recordMapper;


    @Override
    @Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
    public IPage<Record> findRecordPage(Integer pageNum, Integer pageSize, QueryWrapper<Record> queryWrapper) {
        IPage<Record> page = new Page<>(pageNum, pageSize, true);
        IPage<Record> recordPage = recordMapper.findRecordPage(page, queryWrapper);
        return recordPage;
    }

    @Override
    @Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
    public Record findOneRecord(Integer id) {
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("record_Id", id);
        Record record = recordMapper.findOneRecord(queryWrapper);
        return record;
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public int insertRecord(Record record) {
        int insert = recordMapper.insert(record);
        return insert;
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public int updataRecord(Record record) {
        Integer recordId = record.getRecordId();
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("record_Id", recordId);
        int i = recordMapper.updataRecord(record,queryWrapper);
        return i;
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public int deleteRecord(List<Integer> recordId) {
        // 过滤掉 null 元素
        recordId = recordId.stream().filter(Objects::nonNull).collect(Collectors.toList());

        // 打印记录的 ID，用于调试
        System.out.println(recordId);

        // 确保 recordId 不是空列表
        if (!recordId.isEmpty()) {
            // 调用 deleteBatchIds 方法删除记录
            int i = recordMapper.deleteBatchIds(recordId);
            return i;
        } else {
            // 如果 recordId 是空列表，则返回错误代码或者抛出异常，根据你的需求来决定
            return -1; // 或者抛出 IllegalArgumentException 等异常
        }
    }




}
